package com.wiz.web.controllor;

import io.netty.channel.Channel;

import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.BiMap;
import com.wiz.netty.NettyServerCenter;
import com.wiz.web.manager.ServiceManager;

@Controller
@RequestMapping("/work")
public class WorkControllor extends ApplicationObjectSupport{
	
	@Resource
	private ServiceManager serviceManager;
	
	@RequestMapping(value = "/netty/restart", method = RequestMethod.GET)
	@ResponseBody
	public String syncFromClient(HttpServletRequest request,
			HttpSession session, Model model) throws Exception{
		NettyServerCenter nettyCenter = this.getApplicationContext().getBean(NettyServerCenter.class);
		return nettyCenter.restart();
	}
	
	@RequestMapping(value = "/netty/monitor", method = RequestMethod.GET)
	@ResponseBody
	public String nettyMonitor(HttpServletRequest request,
			HttpSession session, Model model) throws Exception{
		BiMap<String, Channel> map = serviceManager.getStationConnectMap();
		Iterator it = map.values().iterator();
		String s = "";
		while(it.hasNext()){
			Channel c = (Channel) it.next();
			s="id="+c.id().asLongText()+" from "+c.remoteAddress().toString()+
					" to "+c.localAddress().toString()+" staus="+c.isActive()+"  "+c.isOpen();
		}
		return s;
	}
	
	@RequestMapping(value = "/netty/clear", method = RequestMethod.GET)
	@ResponseBody
	public String nettyClear(HttpServletRequest request,
			@RequestParam(value = "key") String key,
			HttpSession session, Model model) throws Exception{
		return serviceManager.getStationConnectMap().remove(key).toString();
	}
}
